package com.hzbank.juc.deadlock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: libugu@cskaoyan.com
 * @date 2023/12/25 - 11:20
 */
@Slf4j
public class Philosopher02 extends  Thread{

    Chopstick02 left;
    Chopstick02 right;

    public Philosopher02(String name, Chopstick02 left, Chopstick02 right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        while (true) {
            // 尝试获得左手筷子
            if (left.tryLock()) {
                try {
                    // 尝试获得右手筷子
                    if (right.tryLock()) {
                        try {
                            eat();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        } finally {
                            right.unlock();
                        }
                    }
                } finally {
                    left.unlock();
                }
            }
        }
    }

    private void eat() throws InterruptedException {
        log.debug("eating...");
        TimeUnit.SECONDS.sleep(1);
    }
}
